from selenium import webdriver
from selenium.webdriver.chrome.webdriver import WebDriver
from selenium.webdriver.support.wait import WebDriverWait

from tests.litemall_sys.utils.log_util import logger


class BasePage:
    def __init__(self, driver: WebDriver = None):
        if not driver:
            self.driver = webdriver.Chrome()
            self.driver.implicitly_wait(20)
            self.driver.maximize_window()
        else:
            self.driver = driver

    def find(self, by, value=None):
        if isinstance(by, tuple):
            logger.debug(f'使用{by[0]}的定位方式,进行元素 {by[1]} 的定位')
            ele = self.driver.find_element(*by)
        else:
            logger.debug(f'使用{by}的定位方式,进行元素 {value} 的定位')
            ele = self.driver.find_element(by, value)
        return ele

    def find_click(self, by, value=None):
        ele = self.find(by=by, value=value)
        ele.click()

    def find_and_send(self, by, value=None, text=None):
        ele = self.find(by=by, value=value)
        logger.debug(f'进行信息{text}的输入操作')
        ele.send_keys(text)

    def finds(self, by, value=None):
        if isinstance(by, tuple):
            logger.debug(f'使用{by[0]}的定位方式,进行元素 {by[1]} 的定位')
            eles = self.driver.find_elements(*by)
        else:
            logger.debug(f'使用{by}的定位方式,进行元素 {value} 的定位')
            eles = self.driver.find_elements(by, value)
        return eles

    def wait(self, methond, timeout=30, count=3):
        el = WebDriverWait(self.driver, timeout, count).until(methond)
        return el

    def until_wait(self, button_element, until_ele):
        def inner(driver):
            self.find_click(button_element)
            return self.find(until_ele)
        return inner



